/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ble;

import android.annotation.SuppressLint;
import android.app.Service;
import android.bluetooth.*;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;


/**
 * Service for managing connection and data communication with a GATT server hosted on a
 * given Bluetooth LE device.
 */
@SuppressLint("NewApi") 
public class BluetoothLeService extends Service {
    private final static String TAG = "BluetoothLeService";

    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothGatt mBluetoothGatt;
    
    public BluetoothGattCharacteristic mNotifyCharacteristic;
    public BluetoothGattCharacteristic mNotifyCharacteristic1;

    public BluetoothGattCharacteristic mNotifyBeaconMajorCharacteristic;
    public BluetoothGattCharacteristic mNotifyBeaconMinorCharacteristic; 
    
    
    
    
    public final static String ACTION_GATT_CONNECTED ="action_gatt_connected";
    public final static String ACTION_GATT_DISCONNECTED ="action_gatt_disconnected";
    public final static String ACTION_GATT_SERVICES_DISCOVERED ="action_gatt_services_discovered";
    public final static String ACTION_GATT_IBEACON_SERVICES_DISCOVERED = "action_gatt_ibeacon_services_discovered";
    public static final String ACTION_DATA_BATTERY = "action_data_battery";
    //PM2.5 reading broadcast (广播)
    public final static String ACTION_DATA_PM25 = "action_data_pm25";
    //Temperature, Humidity reading broadcast
    public final static String ACTION_DATA_TEHU = "action_data_tehu";
    public final static String ACTION_DATA_OVER = "action_data_over";
    //Version reading broadcast
    public static final String ACTION_DATA_BLE_VERSION = "action_data_ble_version";
    public final static String EXTRA_DATA ="extra_data";

    public static final int IBEACON = 0x01;
    public static final int DEVICE = 0x02;
    public int mode;
    
    public final static UUID BLE_SERVER =
            UUID.fromString("0000ffb0-0000-1000-8000-00805f9b34fb");
    public final static UUID BLE_NOTIFY =
            UUID.fromString("0000ffb2-0000-1000-8000-00805f9b34fb"); 
    //private String BLEVERSION = "OK+GET:UartBleV";     OK+GET:SerialBle106
    private String BLE_PM25_DATA = "OK+PM25:";
    private String BLE_BATTERY_DATA = "OK+GET"; 
    private String BLE_TEHU_DATA = "OK+TEHU";

    public void writeValue(String strValue) {
    	Log.w(TAG,strValue);
    	mNotifyCharacteristic.setValue(strValue); 
        if (mBluetoothGatt != null) {
            if(mBluetoothGatt.writeCharacteristic(mNotifyCharacteristic)){
            	Log.e(TAG,"writecharacteristic is success");
        	}
            else{
            	Log.e(TAG,"writecharacteristic is error");
            }
        }
    }
     
    public void writeMajor(byte[] strValue) {
    	Log.w(TAG,"1234");
    	
//    	Log.w(TAG,mNotifyBeaconMajorCharacteristic.getUuid().toString());
    	mNotifyBeaconMajorCharacteristic.setValue(strValue); 
    	mNotifyBeaconMajorCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
        if (mBluetoothGatt != null) {
            if(mBluetoothGatt.writeCharacteristic(mNotifyBeaconMajorCharacteristic)){
            	Log.e(TAG,"writecharacteristic is success");
        	}
            else{
            	Log.e(TAG,"writecharacteristic is error");
            }
        }
//        if (mBluetoothGatt != null) {
//            if(mBluetoothGatt.readCharacteristic(mNotifyCharacteristic)){
//            	Log.e(TAG,"writecharacteristic is success");
////            	byte[] data = new byte[2];
////            	data = mNotifyCharacteristic.getValue();
////                Log.d(TAG, String.valueOf(data[0])+ String.valueOf(data[1]));
//        	}
//            else{
//            	Log.e(TAG,"writecharacteristic is error");
//            }
//        }
    }
    
    public void writeMinor(byte[] strValue) {
    	mNotifyBeaconMinorCharacteristic.setValue(strValue); 
    	mNotifyBeaconMinorCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
        if (mBluetoothGatt != null) {
            if(mBluetoothGatt.writeCharacteristic(mNotifyBeaconMinorCharacteristic)){
            	Log.e(TAG,"writecharacteristic is success");
        	}
            else{
            	Log.e(TAG,"writecharacteristic is error");
            }
        }
    }
 /*   
    public boolean checkService(final BluetoothDevice device)
    {
    	for (BluetoothGattService gattService : gattServices) {
    		if (gattService.getUuid().toString().equalsIgnoreCase(UUID_SERVICE.toString()))
    		{
    			return true;
    		}
    	}
    	return false; 
    }
*/
    public void findService(List<BluetoothGattService> gattServices) {
        Log.w(TAG, "findService()--gattService.size" + gattServices.size());
        for (BluetoothGattService gattService : gattServices) {
	    	if (gattService.getUuid().toString().equalsIgnoreCase(BLE_SERVER.toString())) {
	
	    		List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
	        	Log.w(TAG, "findService()--gattCharacteristics.size" + gattCharacteristics.size());
	
	        	for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
	            	if (gattCharacteristic.getUuid().toString().equalsIgnoreCase(BLE_NOTIFY.toString())) {
	                	Log.w(TAG, "findService()--gattCharacteristics" + gattCharacteristic.getUuid());
	                	mNotifyCharacteristic = gattCharacteristic;	
	                	setCharacteristicNotification(gattCharacteristic, true);	                        
	                	broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);                  
	                    break;
	            	}
	         	}
	    	}
        }
    }

    // Implements callback methods for GATT events that the app cares about.  For example,
    // connection change and services discovered.
    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

    	
        /**
         *  与BLE设备的连接状态发生改变时调用
         * @param gatt  BluetoothGatt  代表蓝牙通用规范
         * @param status 上一次的连接状态
         * @param newState  现在的连接状态
         */
    	
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        	Log.w(TAG, String.valueOf(status)+"  "+String.valueOf(newState));
            String intentAction;
            if (status == BluetoothGatt.GATT_SUCCESS) {
                if (newState == BluetoothProfile.STATE_CONNECTED) {
                    intentAction = ACTION_GATT_CONNECTED;

                    broadcastUpdate(intentAction);
                    Log.w(TAG, "Connected to GATT server.");

                    // Attempts to discover services after successful connection.
                    // 一旦发现services 会回调 onServicesDiscovered
                    mBluetoothGatt.discoverServices();
                } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                    intentAction = ACTION_GATT_DISCONNECTED;
                    mBluetoothGatt.close();
                    mBluetoothGatt = null;
                    Log.w(TAG, "Disconnected from GATT server.");
                    broadcastUpdate(intentAction);
                }
            }else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                intentAction = ACTION_GATT_DISCONNECTED;
                mBluetoothGatt.close();
                mBluetoothGatt = null;
                Log.w(TAG, "Disconnected from GATT server.");
                broadcastUpdate(intentAction);
            }
        }

        /**
         *  发现Service时调用
         * @param gatt
         * @param status
         */
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            Log.w(TAG, "onServicesDiscovered() enter function");
            if (status == BluetoothGatt.GATT_SUCCESS) {
                findService(gatt.getServices());
            } else {
                if (mBluetoothGatt.getDevice().getUuids() == null)
                    Log.w(TAG, "onServicesDiscovered received: " + status);
            }
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt,
                                         BluetoothGattCharacteristic characteristic,
                                         int status) {
            Log.w(TAG, "onCharacteristicRead");
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(null, characteristic);
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                                            BluetoothGattCharacteristic characteristic) {
        	 Log.w(TAG, "onCharacteristicChanged");
            broadcastUpdate(null, characteristic);
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
                                          int status) {
        	Log.w(TAG, "onCharacteristicWrite");
        }

        @Override
        public void onDescriptorRead(BluetoothGatt gatt,
                                     BluetoothGattDescriptor bd,
                                     int status) {
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt,
                                      BluetoothGattDescriptor bd,
                                      int status) {
        }

        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, int a, int b) {
            Log.w(TAG, "onReadRemoteRssi");
        }

        @Override
        public void onReliableWriteCompleted(BluetoothGatt gatt, int a) {
            Log.w(TAG, "onReliableWriteCompleted");
        }

    };

    private void broadcastUpdate(final String action) {
        final Intent intent = new Intent(action);
        sendBroadcast(intent);
    }

    private void broadcastUpdate(final String action,
                                 final BluetoothGattCharacteristic characteristic) {
    	Log.w(TAG,"broadcastUpdate() start Receive Data");
        final Intent intent = new Intent();
        String tempAction = action;

        final byte[] data = characteristic.getValue();
        String mData;
		try {
			mData = new String(data, "utf-8");
	        Log.w(TAG,mData);	
	        if(mData.contains("OK+"))
	        {
	        	tempAction = ACTION_DATA_OVER;
	        }
	        Log.w(TAG,"broadcastUpdate() tempaction is "+tempAction);
	        intent.setAction(tempAction);
	        intent.putExtra(EXTRA_DATA, mData);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		sendBroadcast(intent);
//        //处理接收到的数据，区分pm25,温度，湿度，电量值等信息，分流显示  
//        if (data != null && data.length > 0) {
//            Log.w(TAG, "data size" + data.length);
//            String mData;
//            try {
//                mData = new String(data, "utf-8"); 
//                Log.w(TAG, "jon mData" + mData);
//                if (mData.contains(CommConstant.RETRUN_FIRMWARE_NAME)) {
//                    tempAction = ACTION_DATA_BLE_VERSION;     //ble版本信息
//                } else if (mData.contains(BLE_PM25_DATA)) {
//                    tempAction = ACTION_DATA_PM25;                //pm25
//                } else if (mData.contains(BLE_TEHU_DATA)) {
//                    tempAction = ACTION_DATA_TEHU;              //TEHU
//                } else if (mData.contains(BLE_BATTERY_DATA)) {
//                    tempAction = ACTION_DATA_BATTERY;               	
//                }
//                Log.w(TAG,"broadcastUpdate() tempaction is "+tempAction);
//                intent.setAction(tempAction);
//                intent.putExtra(EXTRA_DATA, mData);
//            } catch (UnsupportedEncodingException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//
//        }
//        sendBroadcast(intent);
    }

    public class LocalBinder extends Binder {
        public BluetoothLeService getService() {
            return BluetoothLeService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        // After using a given device, you should make sure that BluetoothGatt.close() is called
        // such that resources are cleaned up properly.  In this particular example, close() is
        // invoked when the UI is disconnected from the Service.
        close();
        return super.onUnbind(intent);
    }

    private final IBinder mBinder = new LocalBinder();

    /**
     * Initializes a reference to the local Bluetooth adapter.
     *
     * @return Return true if the initialization is successful.
     */
    public boolean initialize() {
        // For API level 18 and above, get a reference to BluetoothAdapter through
        // BluetoothManager.
        if (mBluetoothManager == null) {
            mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
            if (mBluetoothManager == null) {
                Log.e(TAG, "Unable to initialize BluetoothManager.");
                return false;
            }
        }

        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
            return false;
        }

        return true;
    }

    /**
     * Connects to the GATT server hosted on the Bluetooth LE device.
     *
     * @param address The device address of the destination device.
     * @return Return true if the connection is initiated successfully. The connection result
     * is reported asynchronously through the
     * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
     * callback.
     */
    public boolean connect(final String address) {
    	Log.w(TAG,address);
    	//this.mode = mode;
        if (mBluetoothAdapter == null || address == null) {
            Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
            return false;
        }


        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        
        if (device == null) {
            Log.w(TAG, "Device not found.  Unable to connect.");
            return false;
        }
        // We want to directly connect to the device, so we are setting the autoConnect
        // parameter to false.
        if (mBluetoothGatt != null) {
            mBluetoothGatt.close();
            mBluetoothGatt = null;
        }
         
        mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
        //mBluetoothGatt.connect();
        int state = mBluetoothManager.getConnectionState(device, BluetoothProfile.GATT);
        Log.d("TAG",String.valueOf(state));
    	if(state == BluetoothProfile.STATE_CONNECTED || state==BluetoothProfile.STATE_DISCONNECTING)
    		return true;
    	
        return true;
    }
/*
    private boolean checkconnectstate(final String address)
    {
    	if(mBluetoothAdapter == null || mBluetoothGatt == null)
    		return false;
    	
    	BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    	
    	
    	
    	return true;
    }
 */   
    /**
     * Disconnects an existing connection or cancel a pending connection. The disconnection result
     * is reported asynchronously through the
     * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
     * callback.
     */
    public void disconnect() {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.disconnect();
    }

    /**
     * After using a given BLE device, the app must call this method to ensure resources are
     * released properly.
     */
    public void close() {
        if (mBluetoothGatt == null) {
            return;
        }
        mBluetoothGatt.close();
        mBluetoothGatt = null;
    }
 
    /**
     * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported
     * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
     * callback.
     *
     * @param characteristic The characteristic to read from.
     */
    public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        Log.e(TAG, "RE 111111111");
        mBluetoothGatt.readCharacteristic(characteristic);
    }

    /**
     * Enables or disables notification on a give characteristic.
     *
     * @param characteristic Characteristic to act on.
     * @param enabled        If true, enable notification.  False otherwise.
     */
    public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                              boolean enabled) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        if(mBluetoothGatt.setCharacteristicNotification(characteristic, enabled))
        	Log.e(TAG, "NOTIFICATION IS SUCCESS" + "  "+ characteristic.getUuid());
        else
        	Log.e(TAG, "notification is error");
        // This is specific to Heart Rate Measurement.
        List<BluetoothGattDescriptor> descriptors=characteristic.getDescriptors();
        for(BluetoothGattDescriptor dp:descriptors){
        	dp.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        	mBluetoothGatt.writeDescriptor(dp);
        }
    }

    /**
     * Retrieves a list of supported GATT services on the connected device. This should be
     * invoked only after {@code BluetoothGatt#discoverServices()} completes successfully.
     *
     * @return A {@code List} of supported services.
     */
    public List<BluetoothGattService> getSupportedGattServices() {
        if (mBluetoothGatt == null) return null;

        return mBluetoothGatt.getServices(); 
    } 
}
